import { Router } from 'express'
import { body, query } from 'express-validator'
import { asyncHandler } from '../middleware/errorHandler'
import { handleValidationErrors, validatePagination } from '../middleware/validation'
import { authenticate, AuthRequest } from '../middleware/auth'
import { ClanService } from '../services/clanService'

const router = Router()
const clanService = new ClanService()

// All routes require authentication
router.use(authenticate)

// Get clan templates
router.get('/templates', validatePagination, asyncHandler(async (req: AuthRequest, res) => {
  const { page, limit, templateType, search } = req.query as any
  const templates = await clanService.getTemplates({ page, limit, templateType, search })
  
  res.json({
    success: true,
    data: templates,
  })
}))

// Create clan template
router.post('/templates', [
  body('title').notEmpty().withMessage('Template title is required'),
  body('content').notEmpty().withMessage('Template content is required'),
  body('templateType').isIn(['ACTIVITY', 'RULE', 'MEETING', 'VENUE']).withMessage('Invalid template type'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const templateData = req.body
  const template = await clanService.createTemplate({ ...templateData, createdBy: req.user!.id })
  
  res.status(201).json({
    success: true,
    data: template,
  })
}))

// Get template by ID
router.get('/templates/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const template = await clanService.getTemplateById(parseInt(id))
  
  if (!template) {
    throw new Error('Template not found')
  }
  
  res.json({
    success: true,
    data: template,
  })
}))

// Update template
router.put('/templates/:id', [
  body('title').optional().notEmpty().withMessage('Template title cannot be empty'),
  body('content').optional().notEmpty().withMessage('Template content cannot be empty'),
  body('templateType').optional().isIn(['ACTIVITY', 'RULE', 'MEETING', 'VENUE']).withMessage('Invalid template type'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const updateData = req.body
  
  const template = await clanService.updateTemplate(parseInt(id), updateData)
  
  res.json({
    success: true,
    data: template,
  })
}))

// Delete template
router.delete('/templates/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  await clanService.deleteTemplate(parseInt(id))
  
  res.json({
    success: true,
    message: 'Template deleted successfully',
  })
}))

// Get comments for template
router.get('/templates/:id/comments', validatePagination, asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const { page, limit } = req.query as any
  
  const comments = await clanService.getComments(parseInt(id), { page, limit })
  
  res.json({
    success: true,
    data: comments,
  })
}))

// Add comment to template
router.post('/templates/:id/comments', [
  body('content').notEmpty().withMessage('Comment content is required'),
  body('parentId').optional().isInt().withMessage('Parent ID must be an integer'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const commentData = req.body
  
  const comment = await clanService.createComment({
    ...commentData,
    templateId: parseInt(id),
    userId: req.user!.id,
  })
  
  res.status(201).json({
    success: true,
    data: comment,
  })
}))

// Get comment by ID
router.get('/comments/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const comment = await clanService.getCommentById(parseInt(id))
  
  if (!comment) {
    throw new Error('Comment not found')
  }
  
  res.json({
    success: true,
    data: comment,
  })
}))

// Update comment
router.put('/comments/:id', [
  body('content').notEmpty().withMessage('Comment content cannot be empty'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const { content } = req.body
  
  const comment = await clanService.updateComment(parseInt(id), content)
  
  res.json({
    success: true,
    data: comment,
  })
}))

// Delete comment
router.delete('/comments/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  await clanService.deleteComment(parseInt(id))
  
  res.json({
    success: true,
    message: 'Comment deleted successfully',
  })
}))

// Get template categories
router.get('/categories', asyncHandler(async (req: AuthRequest, res) => {
  const categories = await clanService.getTemplateCategories()
  
  res.json({
    success: true,
    data: categories,
  })
}))

export { router as clanRouter }